package 设计模式.prototype;

import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.*;

@Data
@NoArgsConstructor
public class Student implements Cloneable, Serializable {
    private String name;
    private Integer age;
    private Student friend;

    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    @Override
    protected Student clone() throws CloneNotSupportedException {
        Student cloneObject = (Student) super.clone();
        cloneObject.friend = cloneObject.getFriend().clone();
        return cloneObject;
    }

    /**
     * 通过序列化的方式深克隆
     */
    public Student deepClone() throws IOException, ClassNotFoundException {
        // 将对象写入流中
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(this);

        //将对象从流中取出
        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bais);
        return (Student) ois.readObject();
    }
}
